package com.mlethe.android.demo.ripple;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.LinearInterpolator;

import androidx.annotation.Nullable;

/**
 * 前进后退动画
 *
 * @author Mlethe
 */
public class FowardBackView extends View {

    private Matrix matrix = new Matrix();

    /**
     * 默认图片资源id
     */
    private int defaultResId = 0;
    /**
     * 默认图片
     */
    private Bitmap defaultBitmap;
    /**
     * 移动的图片资源id
     */
    private int moveResId = 0;
    /**
     * 移动的图片
     */
    private Bitmap moveBitmap;
    private int moveBitmapHeight;
    /**
     * View宽
     */
    private float mWidth;

    /**
     * View高
     */
    private float mHeight;
    private int mMoveHeight;
    private int mTop, mOtherTop;
    private int mAlpha, mOtherAlpha;
    private Paint mPaint;
    private boolean mRunning = false;
    /**
     * 是否是向前 true 是  false 否
     */
    private boolean isFoward = false;

    private ValueAnimator valueAnimator;

    public FowardBackView(Context context) {
        this(context, null);
    }

    public FowardBackView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FowardBackView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (defaultBitmap == null && mWidth > 0 && mHeight > 0) {
            defaultBitmap = createBitmap(matrix, defaultResId, mWidth, mHeight);
        }
        if (moveBitmap == null && mWidth > 0 && mHeight > 0) {
            moveBitmap = createBitmap(matrix, moveResId, mWidth, mHeight);
        }
        if (moveBitmap != null) {
            moveBitmapHeight = moveBitmap.getHeight();
            mMoveHeight = (int) (mHeight - moveBitmapHeight);
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        stopAnimator();
        if (defaultBitmap != null) {
            defaultBitmap.recycle();
            defaultBitmap = null;
        }
        if (moveBitmap != null) {
            moveBitmap.recycle();
            moveBitmap = null;
        }
        if (valueAnimator != null) {
            valueAnimator.cancel();
            valueAnimator = null;
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mWidth = w;
        mHeight = h;
        if (defaultBitmap == null && mWidth > 0 && mHeight > 0) {
            defaultBitmap = createBitmap(matrix, defaultResId, mWidth, mHeight);
        }
        if (moveBitmap == null && mWidth > 0 && mHeight > 0) {
            moveBitmap = createBitmap(matrix, moveResId, mWidth, mHeight);
        }
        if (moveBitmap != null) {
            moveBitmapHeight = moveBitmap.getHeight();
            mMoveHeight = (int) (mHeight - moveBitmapHeight);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (mRunning) {
            if (moveBitmap != null && !moveBitmap.isRecycled()) {
                mPaint.setAlpha(mAlpha);
                canvas.drawBitmap(moveBitmap, 0, mTop, mPaint);
                mPaint.setAlpha(mOtherAlpha);
                canvas.drawBitmap(moveBitmap, 0, mOtherTop, mPaint);
            }
        } else {
            if (defaultBitmap != null && !defaultBitmap.isRecycled()) {
                float top = (mHeight - defaultBitmap.getHeight()) / 2;
                canvas.drawBitmap(defaultBitmap, 0, top, null);
            }
        }
    }

    /**
     * 创建绘制的图像
     *
     * @param matrix
     * @param resId
     * @param width
     * @param height
     * @return
     */
    private Bitmap createBitmap(Matrix matrix, int resId, float width, float height) {
        if (resId != 0) {
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resId);
            int bitmapWidth = bitmap.getWidth();
            int bitmapHeight = bitmap.getHeight();
            matrix.reset();
            // 获取缩放比例
            float scale = 1;
            if (width > 0) {
                scale = width / bitmapWidth;
            }
            if (scale == 1) {
                return bitmap;
            }
            matrix.postScale(scale, scale);
            // 根据缩放比例获取新的位图
            Bitmap createdBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmapWidth, bitmapHeight, matrix, true);
            bitmap.recycle();
            bitmap = null;
            return createdBitmap;
        }
        return null;
    }

    /**
     * 开始动画
     */
    public void startAnimator() {
        if (mMoveHeight <= 0 || mRunning) {
            return;
        }
        int start, end;
        if (isFoward) {
            start = mMoveHeight;
            end = 0;
        } else {
            start = 0;
            end = mMoveHeight;
        }
        valueAnimator = ValueAnimator.ofInt(start, end);
        valueAnimator.setDuration(2000);
        valueAnimator.setRepeatCount(ValueAnimator.INFINITE);
        valueAnimator.setInterpolator(new LinearInterpolator());
        valueAnimator.addUpdateListener(animation -> {
            mTop = (int) animation.getAnimatedValue();
            mOtherTop = mTop + mMoveHeight / 2;
            if (mOtherTop > mMoveHeight) {
                mOtherTop = mTop - mMoveHeight / 2;
            }
            mAlpha = getCurrentAlpha(mTop);
            mOtherAlpha = getCurrentAlpha(mOtherTop);
            postInvalidate();
        });
        mRunning = true;
        valueAnimator.start();
    }

    /**
     * 停止动画
     */
    public void stopAnimator() {
        if (valueAnimator != null && mRunning) {
            mRunning = false;
            valueAnimator.cancel();
        }
    }

    /**
     * 获取当前透明度
     *
     * @param top
     * @return
     */
    private int getCurrentAlpha(int top) {
        int alpha;
        if (top >= mMoveHeight / 2f) {
            float percent = (top - mMoveHeight / 2f) / (mMoveHeight / 2f);
            alpha = 255 - (int) (percent * 255);
        } else {
            float percent = top / (mMoveHeight / 2f);
            alpha = (int) (percent * 255);
        }
        return alpha;
    }

    /**
     * 停止动画显示的图片
     *
     * @param resId
     * @return
     */
    public FowardBackView setDefaultResId(int resId) {
        this.defaultResId = resId;
        if (defaultBitmap == null && mWidth > 0 && mHeight > 0) {
            defaultBitmap = createBitmap(matrix, defaultResId, mWidth, mHeight);
        }
        return this;
    }

    /**
     * 移动的图片资源
     *
     * @param resId
     * @return
     */
    public FowardBackView setMoveResId(int resId) {
        this.moveResId = resId;
        if (moveBitmap == null && mWidth > 0 && mHeight > 0) {
            moveBitmap = createBitmap(matrix, moveResId, mWidth, mHeight);
        }
        if (moveBitmap != null) {
            moveBitmapHeight = moveBitmap.getHeight();
            mMoveHeight = (int) (mHeight - moveBitmapHeight);
        }
        return this;
    }

    /**
     * 设置是否向前
     *
     * @param foward true 是  false 否
     * @return
     */
    public FowardBackView setFoward(boolean foward) {
        isFoward = foward;
        return this;
    }
}
